package cn.tedu.mintmall.service.Impl;

import cn.tedu.mintmall.dto.OrderAddDTO;
import cn.tedu.mintmall.dto.OrderItemAddDTO;
import cn.tedu.mintmall.dto.OrderListTimeDTO;
import cn.tedu.mintmall.dto.OrderStateUpdateDTO;
import cn.tedu.mintmall.entity.Order;
import cn.tedu.mintmall.entity.OrderItem;
import cn.tedu.mintmall.exception.MintmallServiceException;
import cn.tedu.mintmall.mapper.OrderItemMapper;
import cn.tedu.mintmall.mapper.OrderMapper;
import cn.tedu.mintmall.restful.JsonPage;
import cn.tedu.mintmall.restful.ResponseCode;
import cn.tedu.mintmall.service.IOrderService;

import cn.tedu.mintmall.util.GetInfoUtils;
import cn.tedu.mintmall.util.SnowFlakeGenerateIdWorker;
import cn.tedu.mintmall.vo.OrderAddVO;
import cn.tedu.mintmall.vo.OrderListVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private GetInfoUtils getInfoUtils;


    @Override
    public OrderAddVO addOrder(OrderAddDTO orderAddDTO) {
        Order order = new Order();
        BeanUtils.copyProperties(orderAddDTO,order);
        loadOrder(order);
        List<OrderItemAddDTO> orderItemAddDTOS = orderAddDTO.getOrderItems();
        if (orderItemAddDTOS==null || orderItemAddDTOS.isEmpty()){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST,"订单中必须有商品");
        }
        List<OrderItem> orderItems=new ArrayList<>();
        for (OrderItemAddDTO addDTO : orderItemAddDTOS) {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(addDTO,orderItem);
            loadOrderItem(orderItem);
            orderItem.setOrderId(order.getId());
            orderItems.add(orderItem);
            Long skuId = orderItem.getSkuId();
            Integer quantity = orderItem.getQuantity();
            //调用刘旭宁写的根据商品id减少商品库存

        }
        orderItemMapper.insertOrderItems(orderItems);
       // orderMapper.insertOrder(order);
        OrderAddVO addVO = new OrderAddVO();
        addVO.setId(order.getId());
        addVO.setSn(order.getSn());
        addVO.setCreateTime(order.getGmtCreate());
        addVO.setPayAmount(order.getAmountOfActualPay());
        return addVO;
    }

    @Override
    public JsonPage<OrderListVO> listOrdersBetweenTimes(OrderListTimeDTO orderListTimeDTO) {
        validaTimeAndLoadTimes(orderListTimeDTO);
        //时间验证 通过,开始进行查询
        //获得当前用户id
        Long userId = getInfoUtils.getId();
        //将userId赋值给参数
        orderListTimeDTO.setUserId(userId);
        PageHelper.startPage(orderListTimeDTO.getPage(),orderListTimeDTO.getPageSize());
        List<OrderListVO> list = orderMapper.selectOrdersBetweenTimes(orderListTimeDTO);
        return JsonPage.restPage(new PageInfo<>(list));
    }

    @Override
    public void updateOrderState(OrderStateUpdateDTO orderStateUpdateDTO) {
        Order order = new Order();
        BeanUtils.copyProperties(orderStateUpdateDTO,order);
        orderMapper.updateOrderById(order);
    }

    private void validaTimeAndLoadTimes(OrderListTimeDTO orderListTimeDTO){
        //取出起始和结束时间对象
        LocalDateTime start = orderListTimeDTO.getStartTime();
        LocalDateTime end = orderListTimeDTO.getEndTime();
        //若果start和end中有任何一个为null,默认查询一个月内
        if (start==null || end==null){
            //起始时间是当前时间减一个月minusMonths就是减月份的意思,1就是一个月
            start=LocalDateTime.now().minusMonths(7);
            //默认结束时间是当前时间
            end=LocalDateTime.now();
            //赋值给orderListTimeDTO参数
            orderListTimeDTO.setStartTime(start);
            orderListTimeDTO.setEndTime(end);
        }else {
            //如果是国际时间判断,需要添加时区修正来判断时间
            if (end.toInstant(ZoneOffset.of("+8")).toEpochMilli() < start.toInstant(ZoneOffset.of("+8")).toEpochMilli()){
                throw new MintmallServiceException(ResponseCode.BAD_REQUEST,"结束时间应该大于起始时间");
            }
        }
    }

    private void loadOrderItem(OrderItem orderItem) {
        if (orderItem.getSkuId()==null){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST,"订单中商品必须包含skuId");
        }
    }


    private void loadOrder(Order order) {
        if (order.getId()==null){
            SnowFlakeGenerateIdWorker id= new SnowFlakeGenerateIdWorker(1,2);
            order.setId(id.nextId());
        }
        if (order.getUserId()==null){
            order.setUserId(getInfoUtils.getId());
        }
        if (order.getSn()==null){
            order.setSn(UUID.randomUUID().toString());
        }
        if (order.getState()==null){
            order.setState(0);
        }
        if (order.getGmtOrder()==null){
            LocalDateTime now = LocalDateTime.now();
            order.setGmtCreate(now);
            order.setGmtOrder(now);
            order.setGmtModified(now);
        }
        //判断运费,默认为0
        if (order.getAmountOfFreight()==null){
            //默认运费0
            order.setAmountOfFreight(new BigDecimal(0.0));
        }
        //判断优惠,默认为0
        if (order.getAmountOfDiscount()==null){
            order.setAmountOfDiscount(new BigDecimal(0.0));
        }
        if (order.getAmountOfOriginalPrice()==null){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST,"没有提供订单原价");
        }
        BigDecimal freight = order.getAmountOfFreight();
        BigDecimal discount = order.getAmountOfDiscount();
        BigDecimal originalPrice = order.getAmountOfOriginalPrice();
        BigDecimal actualPay = originalPrice.add(freight).subtract(discount);
        order.setAmountOfActualPay(actualPay);
    }


}
